package com.luyu.caffeinedemo.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.luyu.caffeinedemo.config.RepeatSubmitProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;


/**
 * @author luYuHan
 * @date 2023/8/5 15:42
 */
@Component
public class MyCaffeineService {

    @Resource
    private  Cache<String, ArrayList<Cache<String,String>>> cacheAll;
    public  boolean  getData(RepeatSubmitProperty property){
        String key = property.getKey();
        String value = property.getValue();
        ArrayList<Cache<String, String>> oneForValueList = cacheAll.getIfPresent(property.getKey());
        // 无key
        if (CollUtil.isEmpty(oneForValueList)){
            //不存在对应的值,设置对应的值并返回false
            Cache<String, String> cache = Caffeine.newBuilder()
                    .expireAfterWrite(property.getTime(), property.getTimeUnit())
                    .build();
            cache.put(value,key);
            ArrayList<Cache<String, String>> list = new ArrayList<>();
            list.add(cache);
            // 这里可以设置一个用户一个
            cacheAll.put(property.getKey(),list);
            return false;
        }
        // 判断是否存在对应的value,  Cache<String, String>  String=value   String=key
        for (Cache<String, String> singleMethodCache : oneForValueList) {
            String valueKey = singleMethodCache.getIfPresent(value);
            if (StrUtil.isNotBlank(valueKey)){
                return true;
            }
        }
        Cache<String, String> cacheAdd = Caffeine.newBuilder()
                .expireAfterWrite(property.getTime(), property.getTimeUnit())
                .build();
        cacheAdd.put(value,key);
        oneForValueList.add(cacheAdd);
        cacheAll.put(key,oneForValueList);
        return false;
    }

}
